from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField("问题内容", max_length=200)
    pub_date = models.DateTimeField("发布时间")
    
    class Meta:
        verbose_name = '投票问题'
        verbose_name_plural = '投票问题'
        ordering = ['-pub_date']  # 默认按发布时间降序排列
    
    def __str__(self):
        return self.question_text
    
    def was_published_recently(self):
        now = timezone.now()
        return now - timezone.timedelta(days=1) <= self.pub_date <= now
    was_published_recently.boolean = True
    was_published_recently.short_description = '最近发布?'
    was_published_recently.admin_order_field = 'pub_date'
    
    def total_votes(self):
        """计算该问题的总票数"""
        return sum(choice.votes for choice in self.choice_set.all())
    total_votes.short_description = '总票数'

class Choice(models.Model):
    question = models.ForeignKey(Question, verbose_name="所属问题", on_delete=models.CASCADE)
    choice_text = models.CharField("选项内容", max_length=200)
    votes = models.IntegerField("得票数", default=0)
    
    class Meta:
        verbose_name = "投票选项"
        verbose_name_plural = "投票选项"
    
    def __str__(self):
        return self.choice_text